package cn.schoolwow.workflow.test.module.analyzeWorkReport.audit.action;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.workflow.QuickWorkFlow;
import cn.schoolwow.workflow.domain.instance.StartWorkFlowRequest;
import cn.schoolwow.workflow.domain.task.WorkFlowTaskQuery;
import cn.schoolwow.workflow.domain.task.WorkFlowTaskResponse;
import cn.schoolwow.workflow.entity.WorkFlowInstance;
import cn.schoolwow.workflow.test.module.analyzeWorkReport.audit.single.start.StartAnalyzeWorkReportAuditFlow;
import cn.schoolwow.workflow.test.module.analyzeWorkReport.audit.single.start.SubmitAnalyzeWorkReportFlow;
import org.junit.Assert;

import java.util.List;

public class DeleteInstanceTestCaseFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        flowContext.startFlow("执行-分析工作报告-通过审批-测试用例")
                .putTemporaryData("deployName", "分析工作报告审批")
                .next(new StartAnalyzeWorkReportAuditFlow())
                .next(new SubmitAnalyzeWorkReportFlow())
                .execute();

        checkTaskBeforeDelete(flowContext);
        deleteInstance(flowContext);
        checkTaskAfterDelete(flowContext);
    }

    @Override
    public String name() {
        return "分析工作报告-删除工作流实例";
    }

    private void checkTaskBeforeDelete(FlowContext flowContext){
        StartWorkFlowRequest startWorkFlowRequest = flowContext.checkInstanceData(StartWorkFlowRequest.class);
        WorkFlowInstance workFlowInstance = flowContext.checkInstanceData(WorkFlowInstance.class);
        QuickWorkFlow quickWorkFlow = flowContext.checkInstanceData(QuickWorkFlow.class);

        WorkFlowTaskQuery workFlowTaskQuery = new WorkFlowTaskQuery();
        workFlowTaskQuery.instanceIdList.add(workFlowInstance.getId());
        workFlowTaskQuery.assignerList.add(startWorkFlowRequest.contextData.getString("firstAuditUserId"));
        List<WorkFlowTaskResponse> workFlowTaskResponseList = quickWorkFlow.getWorkFlowTaskList(workFlowTaskQuery);
        Assert.assertEquals(1, workFlowTaskResponseList.size());

        flowContext.putInstanceData(workFlowTaskQuery);
    }

    private void deleteInstance(FlowContext flowContext){
        WorkFlowInstance workFlowInstance = flowContext.checkInstanceData(WorkFlowInstance.class);
        QuickWorkFlow quickWorkFlow = flowContext.checkInstanceData(QuickWorkFlow.class);

        quickWorkFlow.deleteWorkFlowInstance(workFlowInstance.getId());
    }

    private void checkTaskAfterDelete(FlowContext flowContext){
        QuickWorkFlow quickWorkFlow = flowContext.checkInstanceData(QuickWorkFlow.class);
        WorkFlowTaskQuery workFlowTaskQuery = flowContext.checkInstanceData(WorkFlowTaskQuery.class);

        List<WorkFlowTaskResponse> workFlowTaskResponseList = quickWorkFlow.getWorkFlowTaskList(workFlowTaskQuery);
        Assert.assertEquals(0, workFlowTaskResponseList.size());
    }

}
